package com.jack.reentrantLock;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

public class reentrantlock {

    private ReentrantLock lock = new ReentrantLock();

    void untimed(){
        boolean captured = lock.tryLock();
        try {
            System.out.println("tryLock: " + captured);
        } finally {
            if(captured){
                lock.unlock();
            }
        }
    }


    void time(){
        boolean captured = false;
        try{
            captured = lock.tryLock(2, TimeUnit.SECONDS);

        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        try{
            System.out.println("tryLock(2, TimeUnit.SECONDS): "+ captured);
        }finally {
            if(captured){
                lock.unlock();
            }
        }


    }


    public static void main(String[] args) throws InterruptedException {
        reentrantlock al = new reentrantlock();
        al.untimed();
        al.time();

        new Thread(){
            {
                setDaemon(true);
            }
            @Override
            public void run() {
                al.lock.lock();
//                al.lock.unlock();
                System.out.println("acquired");
            }
        }.start();

        Thread.sleep(1000l);

        al.untimed();
        al.time();
    }


}
